<template>
  <div class="qrcode-gateway-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <a-spin size="large" />
      <div class="loading-text">正在处理二维码...</div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <div class="error-icon">⚠️</div>
      <h2 class="error-title">处理失败</h2>
      <p class="error-message">{{ error }}</p>
      <div class="error-details" v-if="errorDetails">
        <details>
          <summary>详细信息</summary>
          <pre>{{ errorDetails }}</pre>
        </details>
      </div>
    </div>

    <!-- 显示内容 -->
    <div v-else-if="displayData" class="display-container">
      <!-- 群码类型显示 -->
      <div v-if="displayData.type === 'group'" class="group-display">
        <div v-if="showMainGroup">
          <div class="display-header">
            <h1 class="display-title">{{ displayData.metadata?.mainGroupTitle || '主群二维码' }}</h1>
            <p v-if="displayData.metadata?.mainGroupDesc" class="display-description">{{ displayData.metadata.mainGroupDesc }}</p>
          </div>
          <div class="image-wrapper">
            <img :src="displayData.metadata?.mainGroupImage" :alt="displayData.metadata?.mainGroupTitle || '主群二维码'" class="display-image" @error="handleImageError" />
          </div>
          <div class="group-switch-btn">
            <a-button type="link" v-if="displayData.metadata?.backupGroupImage" @click="showMainGroup = false">若群聊已满，点此加入备用群</a-button>
          </div>
        </div>
        <div v-else>
          <div class="display-header">
            <h1 class="display-title">{{ displayData.metadata?.backupGroupTitle || '备用群二维码' }}</h1>
            <p v-if="displayData.metadata?.backupGroupDesc" class="display-description">{{ displayData.metadata.backupGroupDesc }}</p>
          </div>
          <div class="image-wrapper">
            <img :src="displayData.metadata?.backupGroupImage" :alt="displayData.metadata?.backupGroupTitle || '备用群二维码'" class="display-image" @error="handleImageError" />
          </div>
          <div class="group-switch-btn">
            <a-button type="link" @click="showMainGroup = true">返回主群二维码</a-button>
          </div>
        </div>
      </div>
      <!-- 图片显示 -->
      <div v-else-if="displayData.type === 'image'" class="image-display">
        <div class="display-header">
          <h1 class="display-title">{{ displayData.title || '图片展示' }}</h1>
          <p v-if="displayData.description" class="display-description">{{ displayData.description }}</p>
        </div>
        <div class="image-wrapper">
          <img
            :src="displayData.content"
            :alt="displayData.title || '二维码图片'"
            class="display-image"
            @error="handleImageError"
          />
        </div>
      </div>

      <!-- 文本显示 -->
      <div v-else-if="displayData.type === 'text'" class="text-display">
        <div class="display-header">
          <h1 class="display-title">{{ displayData.title || '文本内容' }}</h1>
        </div>
        <div class="text-wrapper">
          <pre class="display-text">{{ displayData.content }}</pre>
        </div>
        <p v-if="displayData.description" class="display-description">{{ displayData.description }}</p>
      </div>

      <!-- 小程序码显示 -->
      <div v-else-if="displayData.type === 'miniprogram'" class="miniprogram-display">
        <div class="display-header">
          <h1 class="display-title">{{ displayData.title || '小程序' }}</h1>
        </div>
        <div class="miniprogram-wrapper">
          <img
            :src="displayData.content"
            :alt="`${displayData.title}小程序码`"
            class="miniprogram-image"
            @error="handleImageError"
          />
        </div>
        <p class="miniprogram-tip">{{ displayData.description || '请使用微信扫描上方小程序码' }}</p>
      </div>

      <!-- HTML内容显示 -->
      <div v-else-if="displayData.type === 'html'" class="html-display">
        <div v-html="displayData.content" class="html-content"></div>
      </div>

      <!-- 未知类型 -->
      <div v-else class="unknown-display">
        <div class="error-icon">❓</div>
        <h2 class="error-title">未知的显示类型</h2>
        <p class="error-message">不支持的内容类型：{{ displayData.type }}</p>
      </div>
    </div>

    <!-- 重定向信息 -->
    <div v-else-if="redirecting" class="redirect-container">
      <a-spin size="large" />
      <div class="redirect-text">正在跳转到：{{ redirectUrl }}</div>
      <p class="redirect-tip">如果页面没有自动跳转，请<a :href="redirectUrl" target="_blank">点击这里</a></p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import anyRequest from '@/network/anyRequest'

interface DisplayData {
  type: 'image' | 'text' | 'miniprogram' | 'html' | 'group'
  content: string
  title?: string
  description?: string
  metadata?: Record<string, any>
}

interface GatewayResponse {
  qrCodeId: string
  qrCodeName: string
  qrCodeType: number
  qrCodeTypeName: string
  action: 'redirect' | 'display' | 'download'
  redirectUrl?: string
  displayData?: DisplayData
}

const route = useRoute()
const loading = ref(true)
const error = ref('')
const errorDetails = ref('')
const displayData = ref<DisplayData | null>(null)
const redirecting = ref(false)
const redirectUrl = ref('')
const showMainGroup = ref(true)

onMounted(() => {
  // 打印所有路由参数用于调试
  console.log('=== QR Code Gateway 调试信息 ===')
  console.log('完整路由参数:', route.query)
  console.log('当前路由路径:', route.path)
  console.log('当前路由完整信息:', route)
  console.log('================================')

  // 优先从data参数中获取数据（后端重定向模式）
  const dataParam = route.query.data as string

  if (dataParam) {
    console.log('检测到data参数，使用重定向模式处理')
    handleDataFromRedirect(dataParam)
    return
  }

  // 降级方案：使用id和sign参数（直接API调用模式）
  const id = route.query.id as string
  const sign = route.query.sign as string

  console.log('使用API调用模式，参数:', { id, sign })

  if (!id || !sign) {
    error.value = '缺少必要的参数'
    loading.value = false
    return
  }

  handleQrCodeScan(id, sign)
})

function handleDataFromRedirect(dataParam: string) {
  try {
    loading.value = true
    error.value = ''

    console.log('开始解析重定向数据...')
    console.log('原始data参数:', dataParam)

    // 解码URL参数
    const decodedData = decodeURIComponent(dataParam)
    console.log('解码后的数据:', decodedData)

    const response = JSON.parse(decodedData)
    console.log('解析后的JSON数据:', response)

    if (response.code !== 200) {
      throw new Error(response.message || '处理失败')
    }

    const gatewayData = response.data as GatewayResponse
    console.log('网关数据:', gatewayData)
    processGatewayData(gatewayData)

  } catch (err: any) {
    console.error('解析重定向数据失败:', err)
    error.value = '数据解析失败: ' + (err.message || '未知错误')
    errorDetails.value = JSON.stringify(err, null, 2)
  } finally {
    loading.value = false
  }
}

async function handleQrCodeScan(id: string, sign: string) {
  try {
    loading.value = true
    error.value = ''

    console.log('开始API调用，参数:', { id, sign, gateway: false })

    const response = await anyRequest.get('/api/anon/qrcode/scan-json', {
      params: {
        id,
        sign,
        gateway: false // 直接API模式，不使用网关重定向
      }
    })

    console.log('API响应数据:', response.data)

    if (response.data.code !== 200) {
      throw new Error(response.data.message || '处理失败')
    }

    const gatewayData = response.data.data as GatewayResponse
    console.log('网关数据:', gatewayData)
    processGatewayData(gatewayData)

  } catch (err: any) {
    console.error('QR code processing error:', err)
    error.value = err.message || '处理二维码时发生错误'
    errorDetails.value = JSON.stringify(err.response?.data || err, null, 2)
  } finally {
    loading.value = false
  }
}

function processGatewayData(gatewayData: GatewayResponse) {
  console.log('处理网关数据，操作类型:', gatewayData.action)

  if (gatewayData.action === 'redirect') {
    // 处理重定向
    console.log('执行重定向操作，目标URL:', gatewayData.redirectUrl)

    if (gatewayData.redirectUrl) {
      redirecting.value = true
      redirectUrl.value = gatewayData.redirectUrl
      setTimeout(() => {
        console.log('开始执行跳转...')
        window.location.href = gatewayData.redirectUrl!
      }, 500)
    } else {
      throw new Error('重定向URL为空')
    }
  } else if (gatewayData.action === 'display') {
    // 处理显示内容
    console.log('执行显示操作，显示数据:', gatewayData.displayData)
    if (gatewayData.displayData) {
      showMainGroup.value = true // 每次新数据重置为主群
      displayData.value = gatewayData.displayData
    } else {
      throw new Error('显示内容为空')
    }
  } else if (gatewayData.action === 'download') {
    // 处理下载 - 这里可以根据需要实现
    console.log('执行下载操作')
    message.info('下载功能暂未实现')
  } else {
    throw new Error(`不支持的操作类型：${gatewayData.action}`)
  }
}

function handleImageError(event: Event) {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'

  const errorDiv = document.createElement('div')
  errorDiv.className = 'image-error'
  errorDiv.innerHTML = `
    <div class="error-icon">🖼️</div>
    <p>图片加载失败</p>
    <small>图片地址：${img.src}</small>
  `

  img.parentNode?.insertBefore(errorDiv, img.nextSibling)
}
</script>

<style scoped>
.qrcode-gateway-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.loading-container,
.error-container,
.redirect-container {
  text-align: center;
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  width: 100%;
}

.loading-text,
.redirect-text {
  margin-top: 16px;
  font-size: 16px;
  color: #666;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-title {
  font-size: 24px;
  color: #ff4d4f;
  margin-bottom: 12px;
}

.error-message {
  font-size: 16px;
  color: #666;
  margin-bottom: 16px;
}

.error-details {
  margin-top: 20px;
  text-align: left;
}

.error-details pre {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  overflow-x: auto;
}

.display-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  max-width: 600px;
  width: 100%;
}

.display-header {
  padding: 24px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
  text-align: center;
}

.display-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 8px;
}

.display-description {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 图片显示样式 */
.image-wrapper {
  padding: 24px;
  text-align: center;
}

.display-image {
  max-width: 100%;
  max-height: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 文本显示样式 */
.text-wrapper {
  padding: 24px;
}

.display-text {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  border-left: 4px solid #1890ff;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 小程序显示样式 */
.miniprogram-wrapper {
  padding: 24px;
  text-align: center;
}

.miniprogram-image {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.miniprogram-tip {
  margin: 16px 24px 24px;
  font-size: 14px;
  color: #666;
  text-align: center;
}

/* HTML内容显示样式 */
.html-content {
  padding: 24px;
}

.html-content :deep(*) {
  max-width: 100%;
}

/* 未知类型显示样式 */
.unknown-display {
  padding: 40px;
  text-align: center;
}

/* 重定向样式 */
.redirect-tip {
  margin-top: 16px;
  font-size: 14px;
  color: #666;
}

.redirect-tip a {
  color: #1890ff;
  text-decoration: none;
}

.redirect-tip a:hover {
  text-decoration: underline;
}

/* 图片错误样式 */
:deep(.image-error) {
  padding: 20px;
  text-align: center;
  color: #999;
  background: #f5f5f5;
  border-radius: 8px;
  margin-top: 16px;
}

:deep(.image-error .error-icon) {
  font-size: 32px;
  margin-bottom: 8px;
}

:deep(.image-error small) {
  display: block;
  margin-top: 8px;
  word-break: break-all;
}

/* 群码切换按钮样式 */
.group-display .group-switch-btn {
  text-align: center;
  margin: 16px 0 0 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .qrcode-gateway-container {
    padding: 10px;
  }

  .display-container {
    max-width: 100%;
  }

  .display-title {
    font-size: 20px;
  }

  .miniprogram-image {
    width: 160px;
    height: 160px;
  }
}
</style>